package com.jbm;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.rsa.cmbVerifyTools;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONBuilder;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.sql.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by root on 18-6-12.
 */
public class HttpHandler implements com.sun.net.httpserver.HttpHandler
{
	protected static Logger logger = LoggerFactory.getLogger(HttpHandler.class);
	public static Resource m_dialogqueue = new Resource(1000,"dialog");

	public HttpHandler()
	{
	}

	public static String BuildError(int code, String errorinfo)
	{
		JsonObject response = new JsonObject();

		response.addProperty("code",code);
		response.addProperty("errorinfo",errorinfo);

		return response.toString();
	}

	public static String BuildRequest(String content, String sequence,String wy_code)
	{
		JsonObject request = new JsonObject();

		request.addProperty("j_type","request");
		request.addProperty("content",content);
		request.addProperty("sequence",sequence);
		request.addProperty("wy_code",wy_code);

		return request.toString();
	}

	public static String BuildResponse(String content, String sequence)
	{
		JsonObject request = new JsonObject();

		request.addProperty("j_type","response");
		request.addProperty("content",content);
		request.addProperty("sequence",sequence);

		return request.toString();
	}

	public static String BuildKeepalive()
	{
		JsonObject request = new JsonObject();

		request.addProperty("j_type","keepalive");

		return request.toString();
	}

	public static String BuildHello(String wy_code)
	{
		JsonObject request = new JsonObject();

		request.addProperty("j_type","hello");
		request.addProperty("wy_code",wy_code);

		return request.toString();
	}

	@Override
	public void handle(HttpExchange exchange) {
//			String response = "{\"id\":1,\"name\":\"java\",\"ide\":\"eclipse\"}";

		try{

			String method = exchange.getRequestMethod();

//				if ( )

			//获得查询字符串(get)
//				String queryString =  exchange.getRequestURI().getQuery();
//				Map<String,String> queryStringInfo = formData2Dic(queryString);
			//获得表单提交数据(post)

			if ( method.toUpperCase().equals("POST"))
			{
				Headers reqh = exchange.getRequestHeaders();

				String contenttype = reqh.getFirst("Content-type").toLowerCase();

				if ( !contenttype.equals("application/json"))
				{
					exchange.sendResponseHeaders(404,0);
					OutputStream os = exchange.getResponseBody();
					os.close();
				}else
				{
					String postString = IOUtils.toString(exchange.getRequestBody());
					logger.info("Method: " + exchange.getRequestMethod() + " Body:" + postString);
//						Map<String, String> postInfo = formData2Dic(postString);

					String response = null;

					JSONObject jObj = JSONObject.fromObject(postString);
					boolean hasdata = jObj.has("data");
					JSONObject data = null;
					boolean iss = true;

					if ( hasdata )
					{
						data = jObj.getJSONObject("data");
						String sign = jObj.getString("sign");
						iss = cmbVerifyTools.cmbVerify("public.key", data, sign);
					}else
					{
						String lmethod = jObj.getString("method");

						if ( lmethod.equals("create_order") ||
								lmethod.equals("confirm_pay") ||
								lmethod.equals("black") ||
								lmethod.equals("white") ||
								lmethod.equals("get_pay_list") ||
								lmethod.equals("get_contract_info"))
							data = jObj;
						else
							iss = false;
					}

					if (!iss)
						response = BuildError(500, "BAD Request");
					else
					{
						String wy_code = "";

						if ( data.has("wy_code"))
							wy_code = data.getString("wy_code");
						else
							wy_code = "shengning";

						P2PDialog p2pdialog = new P2PDialog(10);
						p2pdialog.Born(5, 6000);
						synchronized (BridgeHnadler.b_server_ca_mutex)
						{
							ConnectAgent ca = BridgeHnadler.b_server_ca.get(wy_code);

							if ( ca != null )
							{
								p2pdialog.Bind_IoSession(ca.getM_iosession());

								m_dialogqueue.Add(p2pdialog);

								String request = BuildRequest(data.toString(), p2pdialog.GetLifeName().toString(), wy_code);

								ca.Send(request);

								response = (String) p2pdialog.Get();
							} else
							{
								response = BuildError(500, wy_code + " Bridge Break");
							}
						}
					}

					Headers h = exchange.getResponseHeaders();

					h.add("Content-type", "application/json");
					h.add("Content-encoding", "utf-8");

					byte[] rb = response.getBytes("UTF-8");

					exchange.sendResponseHeaders(200, rb.length);
					OutputStream os = exchange.getResponseBody();
					os.write(rb);
					os.close();
				}
			}else if ( method.toUpperCase().equals("GET") )
			{
				String uri = exchange.getRequestURI().toString();

				SysLog.g_syslog.MakeLog(SysLog.SYS_LOG_LEVEL_DEBUG,"uri = %s", exchange.getRequestURI().getPath());

				int idx = uri.indexOf("?");

				String params = null;
				Map<String,String> pm = new HashMap<String,String>();

				if ( idx >= 0 )
				{
					params = uri.substring(idx+1);
					String pairs[] = params.split("[&]");

					for (String pair : pairs)
					{
						String param[] = pair.split("[=]");

						String key = "";
						String value = "";
						if (param.length > 0)
						{
							key = URLDecoder.decode(param[0],
									System.getProperty("file.encoding"));
						}

						if (param.length > 1)
						{
							value = URLDecoder.decode(param[1],
									System.getProperty("file.encoding"));
						}
						pm.put(key,value);
						SysLog.g_syslog.MakeLog(SysLog.SYS_LOG_LEVEL_DEBUG,"Param:key=%s value=%s",key,value);
					}

					P2PDialog p2pdialog = new P2PDialog(10);
					p2pdialog.Born(5, 6000);
					synchronized (BridgeHnadler.b_server_ca_mutex)
					{
						ConnectAgent ca = BridgeHnadler.b_server_ca.get("JBM0001");

						if (ca != null)
						{
							p2pdialog.Bind_IoSession(ca.getM_iosession());

							m_dialogqueue.Add(p2pdialog);

							String request = BuildRequest("{\"method\":\"get_pay_list\",\"wy_code\":\""+pm.get("wy_code")+"\",\"openid\":\""+pm.get("openid")+"\"}", p2pdialog.GetLifeName().toString(), pm.get("wy_code"));

							ca.Send(request);

							String response = (String) p2pdialog.Get();

							JsonParser parser = new JsonParser();
							JsonObject req = (JsonObject) parser.parse(response);

							JsonObject jresp = null;

							String tresp = "<!DOCTYPE html>\n" +
									"<html class=''>\n" +
									"<head>\n" +
									"<meta charset='UTF-8'>\n" +
									"<meta name=\"robots\" content=\"noindex\">\n" +
									"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minial-ui\">"+
									"<link rel='stylesheet' href='https://fonts.loli.net/css?family=Roboto:100,300,400,500,700,900|Material+Icons'>\n" +
									"<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/vuetify@1.3.15/dist/vuetify.min.css'>\n" +
									"</head>\n" +
									"<body>\n" +
									"<div id=\"app\">\n" +
									"  <v-app id=\"inspire\">\n" +
									"\n" +
									"\n" +
									"\n" +
									"    <v-layout row>\n" +
									"      <v-flex>\n" +
									"        <v-card>\n" +
									"          <v-toolbar color=\"cyan\" dark>\n" +
									"            <v-toolbar-side-icon></v-toolbar-side-icon>\n" +
									"  \n" +
									"            <v-toolbar-title>订单列表</v-toolbar-title>\n" +
									"  \n" +
									"            <v-spacer></v-spacer>\n" +
									"  \n" +
									"            <v-btn icon>\n" +
									"              <v-icon>search</v-icon>\n" +
									"            </v-btn>\n" +
									"          </v-toolbar>\n" +
									"  \n" +
									"          <v-list two-line>\n" +
									"            <template v-for=\"(item, index) in items\">\n" +
									"              <v-subheader\n" +
									"                v-if=\"item.header\"\n" +
									"                :key=\"item.header\"\n" +
									"              >\n" +
									"              </v-subheader>\n" +
									"  \n" +
									"              <v-divider\n" +
									"                v-else-if=\"item.divider\"\n" +
									"                :inset=\"item.inset\"\n" +
									"                :key=\"index\"\n" +
									"              ></v-divider>\n" +
									"  \n" +
									"              <v-list-tile\n" +
									"                v-else\n" +
									"                :key=\"item.title\"\n" +
									"                avatar\n" +
									"                @click=\"\"\n" +
									"              >\n" +
									" \n" +
									"                <v-list-tile-content>\n" +
									"                  <v-list-tile-title v-html=\"item.title\"></v-list-tile-title>\n" +
									"                  <v-list-tile-sub-title v-html=\"item.subtitle\"></v-list-tile-sub-title>\n" +
									"                </v-list-tile-content>\n" +
									"              </v-list-tile>\n" +
									"            </template>\n" +
									"          </v-list>\n" +
									"        </v-card>\n" +
									"      </v-flex>\n" +
									"    </v-layout>\n" +
									"\n" +
									"\n" +
									"\n" +
									"  </v-app>\n" +
									"</div>\n" +
									"\n" +
									"<script src='https://cdn.jsdelivr.net/npm/vue/dist/vue.js'></script>\n" +
									"<script src='https://cdn.jsdelivr.net/npm/vuetify@1.3.15/dist/vuetify.min.js'></script>\n" +
									"<script >\n" +
									"\n" +
									"\n" +
									"\n" +
									"new Vue({\n" +
									"  el: '#app',\n" +
									"  data: function data() {\n" +
									"    return %s;\n" +
									"\n" +
									"  } \n" +
									"});\n" +
									"\n" +
									"\n" +
									"\n" +
									"</script>\n" +
									"</body></html>";

							if ( req.get("code").getAsInt() == 200 )
							{
								JsonArray rplist = req.getAsJsonArray("content");
								JsonArray plist = new JsonArray();

								int i = 0;
								for(JsonElement rpe: rplist)
								{
									JsonObject pi = new JsonObject();
									JsonObject rp = rpe.getAsJsonObject();

									if ( i > 0 )
									{
										pi.addProperty("divider",true);
										pi.addProperty("inset",true);

										plist.add(pi);
									}
									i++;

									pi = new JsonObject();

									String contract,status,create_date,pay_date,sertype;
									BigDecimal amount;

									contract = rp.get("contract").getAsString();
									amount = rp.get("amount").getAsBigDecimal();
									status = rp.get("status").getAsString();
									create_date = rp.get("create_date").getAsString();
									pay_date = rp.get("pay_date").isJsonNull() ? null :rp.get("pay_date").getAsString();
									sertype = rp.get("ser_type").getAsString();

									switch (sertype)
									{
										case "wy":
											pi.addProperty( "title","合同号:"+contract+" 物业费");
											break;
										case "clean":
											pi.addProperty( "title","合同号:"+contract+" 家政清洁费");
											break;
										default:
											pi.addProperty( "title","合同号:"+contract+" 其他费");
											break;
									}

									String cstatus = null;
									switch (status)
									{
										case "unpay":
											cstatus = "未付款 ";
											break;
										case "paied":
											cstatus = "已付款 ";
											break;
										case "adddate":
											cstatus = "已展期 ";
											break;
										default:
											cstatus = "未知 ";
											break;
									}

									DecimalFormat df = new DecimalFormat();
									df.applyPattern("0.00");

									String st = "<span class='text--primary'>金额:"+df.format(amount)+"</span> &mdash; "+cstatus+" ";
									if ( pay_date != null && !"".equals(pay_date))
										st += "支付时间"+pay_date;
									pi.addProperty("subtitle",st);

									plist.add(pi);
								}

								jresp = new JsonObject();
								jresp.add("items",plist);

								tresp = String.format(tresp,jresp.toString());
							}else
								tresp = String.format(tresp,"{\"items\":[]}");


							Headers h = exchange.getResponseHeaders();

							h.add("Content-type", "text/html");
							h.add("Content-encoding", "utf-8");

							byte[] rb = tresp.getBytes("UTF-8");

							exchange.sendResponseHeaders(200, rb.length);
							OutputStream os = exchange.getResponseBody();
							os.write(rb);
							os.close();
						}
					}
				}else
				{
//					String root = "D:/JBM/GDServer/ForceQuery/get_pay_list/";
//					String uri = exchange.getRequestURI().getPath();
					String response = "<!DOCTYPE html>\n" +
							"<html class=''>\n" +
							"<head>\n" +
							"<meta charset='UTF-8'>\n" +
							"<meta name=\"robots\" content=\"noindex\">\n" +
							"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minial-ui\">"+
							"<link rel='stylesheet' href='https://fonts.loli.net/css?family=Roboto:100,300,400,500,700,900|Material+Icons'>\n" +
							"<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/vuetify@1.3.15/dist/vuetify.min.css'>\n" +
							"</head>\n" +
							"<body>\n" +
							"<div id=\"app\">\n" +
							"  <v-app id=\"inspire\">\n" +
							"\n" +
							"\n" +
							"\n" +
							"    <v-layout row>\n" +
							"      <v-flex>\n" +
							"        <v-card>\n" +
							"          <v-toolbar color=\"cyan\" dark>\n" +
							"            <v-toolbar-side-icon></v-toolbar-side-icon>\n" +
							"  \n" +
							"            <v-toolbar-title>订单列表</v-toolbar-title>\n" +
							"  \n" +
							"            <v-spacer></v-spacer>\n" +
							"  \n" +
							"            <v-btn icon>\n" +
							"              <v-icon>search</v-icon>\n" +
							"            </v-btn>\n" +
							"          </v-toolbar>\n" +
							"  \n" +
							"          <v-list two-line>\n" +
							"            <template v-for=\"(item, index) in items\">\n" +
							"              <v-subheader\n" +
							"                v-if=\"item.header\"\n" +
							"                :key=\"item.header\"\n" +
							"              >\n" +
							"              </v-subheader>\n" +
							"  \n" +
							"              <v-divider\n" +
							"                v-else-if=\"item.divider\"\n" +
							"                :inset=\"item.inset\"\n" +
							"                :key=\"index\"\n" +
							"              ></v-divider>\n" +
							"  \n" +
							"              <v-list-tile\n" +
							"                v-else\n" +
							"                :key=\"item.title\"\n" +
							"                avatar\n" +
							"                @click=\"\"\n" +
							"              >\n" +
							" \n" +
							"                <v-list-tile-content>\n" +
							"                  <v-list-tile-title v-html=\"item.title\"></v-list-tile-title>\n" +
							"                  <v-list-tile-sub-title v-html=\"item.subtitle\"></v-list-tile-sub-title>\n" +
							"                </v-list-tile-content>\n" +
							"              </v-list-tile>\n" +
							"            </template>\n" +
							"          </v-list>\n" +
							"        </v-card>\n" +
							"      </v-flex>\n" +
							"    </v-layout>\n" +
							"\n" +
							"\n" +
							"\n" +
							"  </v-app>\n" +
							"</div>\n" +
							"\n" +
							"<script src='https://cdn.jsdelivr.net/npm/vue/dist/vue.js'></script>\n" +
							"<script src='https://cdn.jsdelivr.net/npm/vuetify@1.3.15/dist/vuetify.min.js'></script>\n" +
							"<script >\n" +
							"\n" +
							"\n" +
							"\n" +
							"new Vue({\n" +
							"  el: '#app',\n" +
							"  data: function data() {\n" +
							"    return {\n" +
							"      items: [\n" +
							"      {\n" +
							"        avatar: 'https://cdn.vuetifyjs.com/images/lists/1.jpg',\n" +
							"        title: 'Brunch this weekend?',\n" +
							"        subtitle: \"<span class='text--primary'>Ali Connors</span> &mdash; I'll be in your neighborhood doing errands this weekend. Do you want to hang out?\" },\n" +
							"\n" +
							"      { divider: true, inset: true },\n" +
							"      {\n" +
							"        avatar: 'https://cdn.vuetifyjs.com/images/lists/2.jpg',\n" +
							"        title: 'Summer BBQ <span class=\"grey--text text--lighten-1\">4</span>',\n" +
							"        subtitle: \"<span class='text--primary'>to Alex, Scott, Jennifer</span> &mdash; Wish I could come, but I'm out of town this weekend.\" },\n" +
							"\n" +
							"      { divider: true, inset: true },\n" +
							"      {\n" +
							"        avatar: 'https://cdn.vuetifyjs.com/images/lists/3.jpg',\n" +
							"        title: 'Oui oui',\n" +
							"        subtitle: \"<span class='text--primary'>Sandra Adams</span> &mdash; Do you have Paris recommendations? Have you ever been?\" }] };\n" +
							"\n" +
							"  } \n" +
							"});\n" +
							"\n" +
							"\n" +
							"\n" +
							"</script>\n" +
							"</body></html>";

					Headers h = exchange.getResponseHeaders();

					h.add("Content-type", "text/html");
					h.add("Content-encoding", "utf-8");

					byte[] rb = response.getBytes("UTF-8");

					exchange.sendResponseHeaders(200, rb.length);
					OutputStream os = exchange.getResponseBody();
					os.write(rb);
					os.close();
				}
			}else
			{
				exchange.sendResponseHeaders(404,0);
				OutputStream os = exchange.getResponseBody();
				os.close();
			}
		}catch (IOException ie) {

			logger.info(ie.getMessage());

		} catch (Exception e) {

			logger.info(e.getMessage());
		}
	}
}
